package com.zjj.rpc.registry;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.alibaba.fastjson.JSON;

public class ServiceRegistry {

	private static final int SERVER_PORT = 2345;

	public static void registry() throws IOException {

		System.out.println("registry service start on port " + SERVER_PORT);
		ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);
		ServerSocket server = new ServerSocket(SERVER_PORT);

		for (;;) {
			try {
				final Socket socket = server.accept();
				Thread thread = new Thread(new Runnable() {
					@Override
					public void run() {
						InputStream input = null;
						try {
							input = new BufferedInputStream(socket.getInputStream());

							String classNameJosn = "";
							byte[] bytes = new byte[1024];
							while (input.read(bytes) != -1) {
								classNameJosn += new String(bytes, "utf-8");
							}
							System.out.println("classNameJson = " + classNameJosn);
							
							List<String> classNameList = JSON.parseArray(classNameJosn,String.class);
//							RegistryServiceHolder.setService(className, clazz);
							
							OutputStream output = new BufferedOutputStream(socket.getOutputStream());
							output.write("success".getBytes("utf-8"));
							output.flush();
							output.close();

						} catch (Exception e) {
							e.printStackTrace();
						} finally {
							try {
								socket.close();
							} catch (IOException e) {
							}
						}
					}
				});
				
				fixedThreadPool.execute(thread);
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

}
